package cn.iocoder.yudao.module.scrm.service.refund;

import cn.iocoder.yudao.module.scrm.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.scrm.dal.mysql.order.OrderMapper;
import cn.iocoder.yudao.module.scrm.enums.common.CrmBizTypeEnum;
import cn.iocoder.yudao.module.scrm.util.CheckNoGeneratorUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.scrm.controller.admin.refund.vo.*;
import cn.iocoder.yudao.module.scrm.dal.dataobject.refund.RefundDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.scrm.dal.mysql.refund.RefundMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.scrm.enums.ErrorCodeConstants.*;

/**
 * 退款 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class RefundServiceImpl implements RefundService {

    @Resource
    private RefundMapper refundMapper;

    @Resource
    private CheckNoGeneratorUtil checkNoGeneratorUtil;

    @Resource
    private OrderMapper orderMapper;

    @Override
    public Long createRefund(RefundSaveReqVO createReqVO) {
        // 插入
        RefundDO refund = BeanUtils.toBean(createReqVO, RefundDO.class);
        //refund.setNo(checkNoGeneratorUtil.generateUniqueCheckNo(CrmBizTypeEnum.CRM_REFUND.getType()));
        OrderDO orderDO = orderMapper.selectById(createReqVO.getOrderId());
        refund.setNo(orderDO.getSystemNumber());
        refund.setOwnerUserId(orderDO.getOwnerUserId());
        refundMapper.insert(refund);
        // 返回
        return refund.getId();
    }

    @Override
    public void updateRefund(RefundSaveReqVO updateReqVO) {
        // 校验存在
        validateRefundExists(updateReqVO.getId());
        // 更新
        RefundDO updateObj = BeanUtils.toBean(updateReqVO, RefundDO.class);
        refundMapper.updateById(updateObj);
    }

    @Override
    public void deleteRefund(Long id) {
        // 校验存在
        validateRefundExists(id);
        // 删除
        refundMapper.deleteById(id);
    }

    private void validateRefundExists(Long id) {
        if (refundMapper.selectById(id) == null) {
            throw exception(REFUND_NOT_EXISTS);
        }
    }

    @Override
    public RefundDO getRefund(Long id) {
        return refundMapper.selectById(id);
    }

    @Override
    public PageResult<RefundDO> getRefundPage(RefundPageReqVO pageReqVO) {
        return refundMapper.selectPage(pageReqVO);
    }

}